package com.edz.dudumifi.utils;

import android.util.Log;

import com.edz.dudumifi.base.Config;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by Corey on 2017/6/12.
 */

public class KKTcpClient {
    private static final String TAG = "KKTcpClient";
    private static KKTcpClient KKTcpClientInstance = null;

    public static KKTcpClient Instance() {
        synchronized (KKTcpClient.class) {
            if (KKTcpClientInstance == null) {
                KKTcpClientInstance = new KKTcpClient();
            }
            return KKTcpClientInstance;
        }
    }

    /**
     * 连接Socket
     *
     * @param strGwIP
     * @param strReqMsg
     * @return
     */
    public String RequestGateway(String strGwIP, String strReqMsg) {

        Socket gwTcpClient;
        //创建输出流对象
        OutputStream mSocketOut;
        //创建输入流对象
        InputStream mSocketIn;
        byte[] readBuf;
        int readLen;

        gwTcpClient = new Socket();
        try {
            gwTcpClient.connect(new InetSocketAddress(strGwIP, Config.local_decice_port), 1000);//原本6677

            gwTcpClient.setSoTimeout(2000);

            mSocketOut = gwTcpClient.getOutputStream();
            mSocketIn = gwTcpClient.getInputStream();

            //发送消息给服务器
            mSocketOut.write(strReqMsg.getBytes());
            readBuf = new byte[2048];

            readLen = mSocketIn.read(readBuf);
            if (readLen > 0) {
                mSocketIn.close();
                mSocketOut.close();
                gwTcpClient.close();
                return new String(readBuf);
            }
        } catch (IOException e) {
            Log.e(TAG, "response" + e.toString());
        }
        return "";
    }

    public String RequestGateway(String strGwIP, String[] strReqMsg) {

        Socket gwTcpClient;
        OutputStream mSocketOut;
        InputStream mSocketIn;
        byte[] readBuf;
        int readLen;

        gwTcpClient = new Socket();
        try {
            gwTcpClient.connect(new InetSocketAddress(strGwIP, 6677), 1000);//原本6677

            gwTcpClient.setSoTimeout(2000);

            mSocketOut = gwTcpClient.getOutputStream();
            mSocketIn = gwTcpClient.getInputStream();

            if (strReqMsg.length > 0) {
                for (int i = 0; i < strReqMsg.length; i++) {
                    mSocketOut.write(strReqMsg[i].getBytes());
                }
            }
            readBuf = new byte[2048];

            readLen = mSocketIn.read(readBuf);
            if (readLen > 0) {
                mSocketIn.close();
                mSocketOut.close();
                gwTcpClient.close();
                return new String(readBuf);
            }
        } catch (Exception e) {
            Log.e(TAG, "response" + e.getMessage());
        }
        return "";
    }
}
